package com.it.jpa.controller;

import cn.hutool.json.JSONUtil;
import com.it.jpa.beans.bo.UserBO;
import com.it.jpa.dao.UserJpaRepository;
import com.it.jpa.model.UserEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * 通过生成的代码来执行sql
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserJpaRepository userRepository;

    @RequestMapping("/saveUser")
    public UserEntity saveUser(@RequestBody UserBO userBO) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userBO,userEntity);

        return userRepository.save(userEntity);
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(@RequestBody UserBO userBO) {

        userRepository.deleteById(userBO.getId());
    }

    @RequestMapping("/updateUser")
    public String updateUser(@RequestBody UserBO userBO) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userBO,userEntity);
        userRepository.saveAndFlush(userEntity);
        return "OK";
    }

    @RequestMapping("/getUserInfo")
    public String getUserInfo(@RequestBody UserBO userBO) {

        Optional<UserEntity> optional = userRepository.findById(userBO.getId());
        UserEntity userEntity = optional.orElseGet(UserEntity::new);
        return JSONUtil.parse(userEntity).toString();
    }



}
